//
//  USLoveCompassViewController.m
//  us
//
//  Created by karry on 2025/4/7.
//

#import "USLoveCompassViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
#import "RadarPulseView.h"
#import "USLoveCompassUserHeader.h"
#include "USRealtimeLocationManager.h"

@interface USLoveCompassViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, strong) UIImageView *pointerImageView;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UILabel *distanceLabel;
@property (nonatomic, strong) UILabel *directionLabel;
@property (nonatomic, strong) CLLocation *targetLocation;
@property (nonatomic, strong) CAEmitterLayer *particleLayer;
@property (nonatomic, assign) BOOL isParticleActive;
@property (nonatomic, strong) UIImpactFeedbackGenerator *feedbackGenerator;

@property (nonatomic, strong) UIButton *hitButton;
@property (nonatomic, strong) RadarPulseView *radar;

@property (nonatomic, strong) UIImage *arrowImage;

@property (nonatomic,strong) USLoveCompassUserHeader *header;
@property (nonatomic,strong) UILabel *userStateLab;


@end

@implementation USLoveCompassViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self sendMsgAction:@"appear_compass"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [self sendMsgAction:@"disappear_compass"];
 
}

- (void)sendMsgAction:(NSString *)msgAction{
    
    EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:msgAction];
    body.isDeliverOnlineOnly = YES; // 不存消息
    EMChatMessage *msg = [[EMChatMessage alloc] initWithConversationID:USUser.user.relImUserName body:body ext:nil];
    
    [[EMClient sharedClient].chatManager
     sendMessage:msg
     progress:nil
     completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        if (error) {
            NSLog(@"%@失败",msgAction);
        }else{
            NSLog(@"%@成功",msgAction);
        }
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"恋爱指南针";

    [self setupUI];
    [self setupLocationManager];

    self.feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleRigid];
    [self.feedbackGenerator prepare];

    
    [self reloadTargetLocation];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadTargetLocation) name:USNotificationRelUserLocationChange object:nil];
    
}

- (void)reloadTargetLocation{
    
    USLocationInfo *locationInfo = [[USRealtimeLocationManager shared]relUserLocationInfo];
    if (!locationInfo) {
        
        // 设置男朋友的位置（例子：北京天安门）
//        self.targetLocation = [[CLLocation alloc] initWithLatitude:39.9087 longitude:116.3975];
        self.userStateLab.text = @"未获取到对方的位置，请通知他打开us，并检查位置权限哦";
        
    }else{
        
        NSString *latString = locationInfo.lat;
        NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:latString];
        double lat = [decimal doubleValue];
        
        NSString *latString1 = locationInfo.lng;
        NSDecimalNumber *decimal1 = [NSDecimalNumber decimalNumberWithString:latString1];
        double lng = [decimal1 doubleValue];
        self.targetLocation = [[CLLocation alloc]initWithLatitude:lat longitude:lng];
        
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:locationInfo.timestamp];
        self.userStateLab.text = [NSDate jk_timeInfoWithDate:date];
    }
    [self updateLocationInfo];

}


- (void)setupUI {
    
    self.header = [[USLoveCompassUserHeader alloc]initWithFrame:CGRectMake(0, 0, 38, 38)];
    self.navigationItem.titleView = self.header;
    
    self.userStateLab = [UILabel new];
    self.userStateLab.font = [UIFont systemFontOfSize:14];
    self.userStateLab.textColor = UIColor.grayColor;
    self.userStateLab.text = @"更新于xxx";
    self.userStateLab.textAlignment = NSTextAlignmentCenter;
    self.userStateLab.numberOfLines = 0;
    [self.view addSubview:self.userStateLab];
    [self.userStateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(12);
        make.right.mas_offset(-12);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).mas_offset(4);
    }];
    
    
    UIImageSymbolConfiguration *boldConfig = [UIImageSymbolConfiguration configurationWithWeight:UIImageSymbolWeightHeavy];
    UIImage *image = [UIImage systemImageNamed:@"arrow.up" withConfiguration:boldConfig];
    self.arrowImage = image;
    self.pointerImageView = [[UIImageView alloc] initWithImage:image];
    self.pointerImageView.tintColor = UIColor.systemBlueColor;
    self.pointerImageView.frame = CGRectMake(0, 0, 200, 200);
    self.pointerImageView.center = CGPointMake(self.view.center.x, self.view.center.y - 80);
    self.pointerImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.pointerImageView];

    self.statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.pointerImageView.frame) + 16, self.view.bounds.size.width, 30)];
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.font = [UIFont boldSystemFontOfSize:18];
    self.statusLabel.textColor = UIColor.systemGrayColor;
    self.statusLabel.text = @"正在搜索方向...";
    self.statusLabel.hidden = YES;
    [self.view addSubview:self.statusLabel];

    self.distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.statusLabel.frame) + 8, self.view.bounds.size.width, 24)];
    self.distanceLabel.font = [UIFont systemFontOfSize:40];
    self.distanceLabel.text = @"距离未知";
    [self.view addSubview:self.distanceLabel];
    
    self.directionLabel = [UILabel new];
    self.directionLabel.font = [UIFont systemFontOfSize:40];
    self.directionLabel.adjustsFontSizeToFitWidth = YES;
    self.directionLabel.minimumScaleFactor = 0.5;
    self.directionLabel.text = @"方向";
    [self.view addSubview:self.directionLabel];
    
    UIButtonConfiguration *config = [UIButtonConfiguration tintedButtonConfiguration];
    config.title = @"戳他";
    config.cornerStyle = UIButtonConfigurationCornerStyleCapsule;
    
    self.hitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.hitButton.configuration = config;
    self.hitButton.tintColor = UIColor.whiteColor;
    [self.view addSubview:self.hitButton];
    [self.hitButton addTarget:self action:@selector(remindAction) forControlEvents:UIControlEventTouchUpInside];
 
    
    RadarPulseView *radar = [[RadarPulseView alloc]initWithFrame:self.view.bounds];
    [self.view insertSubview:radar atIndex:0];
    self.radar = radar;
    
    [self.directionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-40);
    }];
    
    [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(self.directionLabel.mas_top).mas_offset(-6);
    }];
    
    [self.hitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-20);
        make.bottom.mas_equalTo(self.directionLabel);
        make.width.height.mas_equalTo(60);
    }];
    
}
#pragma mark - 戳一戳
- (void)remindAction {
    [USFeedbackTool impactSoft];

//    再对准一点，就能拥抱啦!
 
//    xx提醒你开启指南针
//    让Ta找到爱的方向
    
//     xx戳了下你
//  别动，TA快要朝你扑过来了
    
    NSString *action_title = [NSString stringWithFormat:@"%@戳了下你",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":@"",
                          @"action_title":action_title,
                          @"action_content":@"别动，Ta快要朝你扑过来了！"};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_Location andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_Location andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_Location) forKey:@"type"];
    [param setValue:@"" forKey:@"pkId"];
    [param setValue:@"戳了下你" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];

    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}
- (void)setupLocationManager {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager requestAlwaysAuthorization];

    if ([CLLocationManager headingAvailable]) {
        self.locationManager.headingFilter = kCLHeadingFilterNone;
        [self.locationManager startUpdatingHeading];
    }

    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    [self.locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    self.currentLocation = locations.lastObject;
    [self updateLocationInfo];
}


- (void)updateLocationInfo{
    
    if (self.currentLocation == nil || self.targetLocation == nil) {
        return;
    }
    
    NSLog(@"%@ - %@",@(self.currentLocation.coordinate.latitude),@(self.targetLocation.coordinate.latitude));
    
    CLLocationDistance distance = [self.currentLocation distanceFromLocation:self.targetLocation];
    
    BOOL isKM = distance >= 1000;
    NSString *valueStr = isKM ? [NSString stringWithFormat:@"%.2f", distance / 1000.0] : [NSString stringWithFormat:@"%.0f", distance];
    NSString *unitStr = isKM ? @" 公里" : @" 米";
    NSString *fullStr = [NSString stringWithFormat:@"%@%@", valueStr, unitStr];

    // 创建富文本
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:fullStr];

    // 设置红色（数值部分）
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor systemBlueColor] range:NSMakeRange(0, valueStr.length)];

    // 设置黑色（单位部分）
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor secondaryLabelColor] range:NSMakeRange(valueStr.length, unitStr.length)];

    self.distanceLabel.attributedText = attrStr;

}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    if (!self.currentLocation || !self.targetLocation) return;

    double bearing = [self bearingToLocation:self.targetLocation fromLocation:self.currentLocation];
    double angle = bearing - newHeading.trueHeading;
    if (angle > 180) angle -= 360;
    if (angle < -180) angle += 360;

    CGFloat radians = angle * M_PI / 180.0;

    [UIView animateWithDuration:0.2 animations:^{
        self.pointerImageView.transform = CGAffineTransformMakeRotation(radians);
    }];

    CGFloat diff = fabs(angle);
    static BOOL hasVibrated = NO;
    if (diff < 10) {
        
        self.statusLabel.text = @"❤️ 正对他啦！";
        self.statusLabel.textColor = [UIColor mainRedColor];
        self.pointerImageView.tintColor = [UIColor mainRedColor];
        if (!hasVibrated) {
            hasVibrated = YES;
            [self.feedbackGenerator impactOccurred];
        }
        self.view.backgroundColor = UIColor.mainRedColor;
        self.pointerImageView.tintColor = UIColor.whiteColor;
        
        [self startParticlesIfNeeded];

        [UIView animateWithDuration:0.6 delay:0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat animations:^{
            self.pointerImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(radians), 1.05, 1.05);
        } completion:nil];
        
        [self.radar start];
        self.hitButton.hidden = NO;
        
    } else {
        self.hitButton.hidden = YES;
        self.view.backgroundColor = UIColor.mi_1_color;
        self.pointerImageView.tintColor = UIColor.systemBlueColor;
        hasVibrated = NO;
        self.statusLabel.text = @"正在对准方向中...";
        self.statusLabel.textColor = UIColor.systemGrayColor;
        self.pointerImageView.transform = CGAffineTransformMakeRotation(radians);

        [self stopParticlesIfNeeded];
        [self.radar stop];
    }
    
    NSString *msg = [self relativeDirectionToTarget];
    self.directionLabel.text = msg;
    
}

- (void)startParticlesIfNeeded {
        
    if (self.isParticleActive) return;
    self.isParticleActive = YES;

    self.particleLayer = [CAEmitterLayer layer];
    self.particleLayer.emitterPosition = self.pointerImageView.center;
    self.particleLayer.emitterShape = kCAEmitterLayerCircle;
    self.particleLayer.emitterSize = CGSizeMake(50, 50);

    CAEmitterCell *cell = [CAEmitterCell emitterCell];
    cell.birthRate = 5;
    cell.lifetime = 3.0;
    cell.velocity = 50;
    cell.scale = 0.05;
    cell.scaleRange = 0.02;
    cell.alphaSpeed = -0.4;
    cell.emissionRange = M_PI * 2;
    cell.contents = (id)[[UIImage imageNamed:@"style_love"] CGImage];

    self.particleLayer.emitterCells = @[cell];
    [self.view.layer addSublayer:self.particleLayer];
}

- (void)stopParticlesIfNeeded {

    if (!self.isParticleActive) return;
    self.isParticleActive = NO;
    [self.particleLayer removeFromSuperlayer];
    self.particleLayer = nil;
}

- (double)bearingToLocation:(CLLocation *)destination fromLocation:(CLLocation *)origin {
    double lat1 = origin.coordinate.latitude * M_PI / 180.0;
    double lon1 = origin.coordinate.longitude * M_PI / 180.0;

    double lat2 = destination.coordinate.latitude * M_PI / 180.0;
    double lon2 = destination.coordinate.longitude * M_PI / 180.0;

    double dLon = lon2 - lon1;
    double y = sin(dLon) * cos(lat2);
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
    double bearing = atan2(y, x);
    return bearing * 180.0 / M_PI; // 返回角度
}

- (NSString *)relativeDirectionToTarget {
    if (!self.currentLocation || !self.targetLocation) return @"未知";

    double bearing = [self bearingToLocation:self.targetLocation fromLocation:self.currentLocation];
    double heading = self.locationManager.heading.trueHeading;
    double angle = bearing - heading;

    // 归一化到 [-180, +180]
    if (angle > 180) angle -= 360;
    if (angle < -180) angle += 360;

    if (fabs(angle) <= 10) {
        return @"正对着啦！";
    }else if (fabs(angle) <= 45) {
        return @"再对准一点，就能拥抱啦!";
    } else if (angle > 45 && angle <= 135) {
        return @"右侧";
    } else if (angle < -45 && angle >= -135) {
        return @"左侧";
    } else {
        return @"后方";
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
